/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
import java.sql.*;

@WebServlet(name = "Servlet", urlPatterns = {"/Servlet"})
public class Servlet extends HttpServlet {
   static String login = "root";
   static String password = "santiago";
   private String nombre=null;
   private String apellido = null;
   private String usuario = null;
   private String clave = null;
   Connection connect = null;
      
   public void init(ServletConfig config) throws ServletException {
       super.init(config);
       String url = new String("jdbc:mysql://localhost/usuario");       
       try{
         Class.forName("com.mysql.jdbc.Driver");           
       }catch(ClassNotFoundException e){
           System.out.println("Error al cargar el driver");
           System.out.println(e.getMessage());
       }try{
           connect = (Connection) DriverManager.getConnection(url,login,password);              
       }catch(SQLException sqlEx){
           System.out.println("Se ha producido un error al"+"establecer la conexion con: "+url);
           System.out.println(sqlEx.getMessage());
       }
       System.out.println("Iniciando Servlet ....");
   }
   
    public void destroy(){
        super.destroy();
        System.out.println("Cerrando conexion...");
        try {
            connect.close();
        }catch(SQLException e){
            System.out.println("No se pudo cerrar la conexion");
            System.out.println(e.getMessage());
        }
            
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int status = ingresar(request.getParameter("Usuario"),request.getParameter("clave"));
        switch(status) {
          case 0:
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Datos</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Datos</h1>");
            out.println("Nombre: "+nombre+"<br>");
            out.println("Apellido: "+apellido);
            out.println("</body>");
            out.println("</html>");
            break;
          case 1:
            response.sendRedirect("index.jsp?status=1");
            break;              
        }             

    }

    public int  ingresar(String usuario, String contrase)
    {
        int status = 1;
        ResultSet miRs = null;
        String miQuery = "SELECT * FROM usuario WHERE usuario=? and clave=?" ;
      
        try
            {PreparedStatement miStm = (PreparedStatement) connect.prepareStatement(miQuery);
             miStm.setString(1, usuario);
             miStm.setString(2, contrase);
             miRs = miStm.executeQuery();
             if (miRs.next()){
              apellido = miRs.getString("Apellido");
              nombre = miRs.getString("Nombre");
              status = 0;
             }
            }
            catch (SQLException ex){
                System.out.println("Se ha producido un error al realizar la consulta");
            }
          return status;
    } 
    
    public int BuscarUsuario (String DNI){
        int status=1;
        ResultSet miRs = null;
        String myQuery = "Select dni from Usuario where dni=?";
        
        try{
          PreparedStatement miStm = (PreparedStatement) connect.prepareStatement(myQuery); 
          miStm.setString(1, DNI);
          miRs = miStm.executeQuery("DNI");
          if (miRs.next()) status = 0;
          }catch (SQLException ex){}        
        return status;
    }
    
    public int InsertarUsuario(String nombre, String apellido, String tipo, String dni, String email, String usuario, String pass){
     int status=0;
     
     int pers = BuscarUsuario("dni");
     
     if (pers !=0){
         String myQuery ="Insert into Usuario (nombre,apellido,tipo,dni,emal,usuario,pass) values (?,?,?,?,?,?,?)";
         try{
          PreparedStatement miStm = (PreparedStatement) connect.prepareStatement(myQuery);
          miStm.setString (1,nombre);
          miStm.setString(2, apellido);
          miStm.setString(3, tipo);
          miStm.setString(4, dni);
          miStm.setString(5, email);
          miStm.setString(6, usuario);
          miStm.setString(7, pass);
          status = miStm.executeUpdate();
         }catch (SQLException ex){status = 3;}        
     } else {status=2;}     
     return status;
    }

    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
